//
//  VideoQuestionsVC.m
//  ATAInterview
//
//  Created by up72-17 on 2018/12/11.
//  Copyright © 2018 up72-17. All rights reserved.
//

#import "VideoQuestionsVC.h"

@interface VideoQuestionsVC ()

@end

@implementation VideoQuestionsVC


- (void)dealloc {
    NSLog(@"VideoQuestionsVC dealloc");
}

#pragma mark - 移除通知和观察者
- (void)removeObserveAndNOtification{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (videoPlayer != nil) {
        [videoPlayer removeTimeObserver:playTimeObserver]; // 移除playTimeObserver}
        [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
        [playerItem removeObserver:self forKeyPath:@"status"];
        videoPlayer = nil;
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [playerSlider setThumbImage:[UIImage imageNamed:@"视频进度圆点"] forState:UIControlStateNormal];

    [playerSlider setMinimumTrackImage:[UIImage imageNamed:@"视频进度min"] forState:UIControlStateNormal];
    [playerSlider setMaximumTrackImage:[UIImage imageNamed:@"视频进度max"] forState:UIControlStateNormal];
    
    
    [MTool setViewRadius:70 view:circleView];
    
    [timeLabel setText:@"00:30"];
    
    [titleLable setText:@"模拟试题1/4"];
    
    [questionsTitleLabel setText:@"问题一"];
    
    
    myProgressView.transform = CGAffineTransformMakeScale(1.0, 4.0);
    
    [myProgressView setProgressTintColor:kColorWithRGB(0x00D985)];
    [myProgressView setTrackTintColor:kColorWithRGB(0xD1F8E9)];
    
    [MTool setViewRadius:6 view:myProgressView];
    
    timeIndex = 30;
    
    [myProgressView setProgress:0];
    
    myTime = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timeing) userInfo:nil repeats:YES];

    fiveTime = [NSTimer timerWithTimeInterval:0.1f target:self selector:@selector(startFiveProgress) userInfo:nil repeats:YES];
    
    
    
    NSMutableArray *images = [NSMutableArray array];
    
    UIImage *image_1 = [UIImage imageNamed:@"语音_1"];
    UIImage *image_2 = [UIImage imageNamed:@"语音_2"];
    UIImage *image_3 = [UIImage imageNamed:@"语音_3"];
    [images addObject:image_1];
    [images addObject:image_2];
    [images addObject:image_3];
    
    processView = [[SABCircleProcessView alloc] initWithFrame:fiveSecondsContentBackView.bounds];
    [fiveSecondsContentBackView addSubview:processView];
    processView.ovalShapeLayer.strokeEnd = 1;
    
    [self initVideo];
    
}



- (IBAction)backButtonAction:(id)sender {
    [self releaseMe];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)initVideo {
    NSString *videoPath = [[NSBundle mainBundle] pathForResource:@"12" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:videoPath];
    
    playerItem = [AVPlayerItem playerItemWithURL:url];
    videoPlayer = [AVPlayer playerWithPlayerItem:playerItem];

    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:videoPlayer];
    layer.frame = videoBackView.bounds;

    [videoBackView.layer addSublayer:layer];
    [self play];
    
    // 注册观察者，通知
    [self addObserverAndNotification];
    
    [videoBackView bringSubviewToFront:controlView];
}

#pragma mark - 观察者、通知
- (void) addObserverAndNotification {
    // 观察status属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:(NSKeyValueObservingOptionNew) context:nil];
    [playerItem addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew) context:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

#pragma mark - observe
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *item = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue]; // 获取更改后的状态
        if (status == AVPlayerStatusReadyToPlay) {
            CMTime duration = item.duration; // 获取视频长度
            // 设置视频时间
            [self setMaxDuration:CMTimeGetSeconds(duration)];
            // 播放
            [self play];
            //监听播放进度
            [self monitoringPlayback:playerItem];
        } else if (status == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
        } else {
            NSLog(@"AVPlayerStatusUnknown");
        }
        
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
//        NSTimeInterval timeInterval = [self availableDuration]; // 缓冲时间
//        CGFloat totalDuration = CMTimeGetSeconds(_playerItem.duration); // 总时间
//        CGFloat progress = timeInterval / totalDuration;
//        //在这里设置缓存进度
//        [self.progressView setProgress:progress animated:YES]; // 更新缓冲条
    }
}


#pragma mark - 观察播放进度
- (void)monitoringPlayback:(AVPlayerItem *)item {
    __weak typeof(self)WeakSelf = self;
    // 观察间隔, CMTime 为30分之一秒
    playTimeObserver = [videoPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 30.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        // 获取 item 当前播放秒
        float currentPlayTime = (double)item.currentTime.value / item.currentTime.timescale;
        [WeakSelf updateVideoSlider:currentPlayTime];
        // 更新slider, 如果正在滑动则不更新
//        if (_isSliding == NO) {
//            [WeakSelf updateVideoSlider:currentPlayTime];
//        }
    }];
}

#pragma mark - 播放完成后
- (void)playbackFinished:(NSNotification *)notification {
    NSLog(@"视频播放完成通知");
    playerItem = [notification object];
    [playerItem seekToTime:kCMTimeZero]; // item 跳转到初始
    //[_player play]; // 循环播放
}

#pragma mark - 设置播放seconds
- (void) updateVideoSlider:(float) time {
//    NSLog(@"time=%f",time);
    [playerNowTimeLabel setText:[NSString stringWithFormat:@"%@/", [MTool convertTime:time]]];
    playerSlider.value = time;
}

#pragma mark - 获取缓存进度
- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[videoPlayer currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}




#pragma mark - 设置视频时间总秒数
- (void) setMaxDuration:(CGFloat)seconds {
    playerSlider.minimumValue = 0;
    playerSlider.maximumValue = seconds;
//    self.totalSeconds = seconds;
    [playerTimeLabel setText:[MTool convertTime:seconds]];
    NSLog(@"总秒数===%f",seconds);
}

#pragma mark - 播放
- (void) play{
    [videoPlayer play];
}

#pragma mark - 暂停
- (void) pause {
    [videoPlayer pause];
}







- (void)timeing {
   
    if (timeIndex <= 0) {
        [myTime invalidate];
        [self startButtonAction:nil];
    }
    
    if (timeIndex == 5) {
        fiveTimeIndex = 50;
        [[NSRunLoop currentRunLoop] addTimer:fiveTime forMode:NSRunLoopCommonModes];
        [fiveSecondsView setHidden:NO];
        
    }
    [fiveSecondsLabel setText:[NSString stringWithFormat:@"%ld", (long)timeIndex]];
    
    [timeLabel setText:[MTool convertTime:timeIndex]];
    [myProgressView setProgress:(30.0f - (CGFloat)timeIndex) / 30.0f];
    
    
    timeIndex--;
    
    //    NSLog(@"timeIndex = %ld", (long)timeIndex);
}

- (void)startFiveProgress {
    
    fiveTimeIndex--;
    
    if (fiveTimeIndex <= 0) {
        [fiveSecondsView setHidden:YES];
        [fiveTime invalidate];
    }
    
    processView.ovalShapeLayer.strokeEnd = ((CGFloat)fiveTimeIndex) / 50.0f;
    
}


- (IBAction)startButtonAction:(id)sender {
    [self releaseMe];
    AnswerVC *answer = [[AnswerVC alloc] init];
    [self.navigationController pushViewController:answer animated:YES];
}


- (void)releaseMe {
    [self pause];
    if (myTime.isValid) {
        [myTime invalidate];
    }
    if (fiveTime.isValid) {
        [fiveTime invalidate];
    }
    [self removeObserveAndNOtification];
    
}

@end
